/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var virtualLink = require("mlib/util/virtualLink");
var ajax = require("mlib/io/ajax");
var swiper = require("mlib/util/swiper");
var closest = require("mlib/dom/closest");
var touch = require("mlib/evt/touch");

var calendar =require("../plugin/date/calendar"); // 日历函数

var render = require("./list.ejs"); // 页面模板

module.exports = function(node, opts) {
	
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	
    var navIndex=0; 
    var slider_swiper = null;
    var nav_swiper = null;
    var goods_swiper = null;
    var loading =false;
	

	var m_sliswiper = null;
	var m_navswiper = null;
	var m_conswiper = null;
    var shareData = null;
	var m_itempos = null;
	var m_sw = null;
	
	
    //-------------事件响应声明---------------
    var evtFuncs = {
            scroller:function(evt){
                var el = evt.target,scrolledH = el.clientHeight*1.2 + el.scrollTop;
                if(scrolledH >= el.scrollHeight) {
                    var tabIndex = goods_swiper.activeIndex,curnav =nav_swiper.slides[tabIndex],isLoaded = curnav.getAttribute("data-loaded"),pIndex=curnav.getAttribute("data-page"),cid=curnav.getAttribute("data-cid");
                    if(isLoaded){return;}
					custFuncs.loaddata(parseInt(pIndex)+1,tabIndex);
                }
            }
    }

    //-------------子模块实例化---------------
    var initMod = function() {
		
        slider_swiper = new swiper("#slider-swiper", {                  
            "autoplay": 5E3,
            "onTransitionEnd": function(swiper) {
                m_sliswiper.forEach(function(item, index) {
                    if (index == swiper.activeIndex) {
                        item.style.zIndex = 2;
                    } else {
                        item.style.zIndex = 0;
                    }
                });
            },
			"onInit": function(swiper){
				m_sliswiper = [].slice.call(swiper.slides);
			},
            "speed": 1E3,
            "effect" : 'fade',
            "lazyLoading" : !0,
            "touchMoveStopPropagation": !1,
            "pagination": '.swiper-pagination'
        });        

        nav_swiper = new swiper('#nav-swiper',{
            "watchSlidesProgress" : !0,
            "watchSlidesVisibility" : !0,
            "slidesPerView" : data.categoryNav.length >3 ? 4 : data.categoryNav.length,
            "onInit": function(swiper){
				var vnum = swiper.params.slidesPerView;
				m_sw = (100/vnum);
				m_itempos = (m_sw-7.8125)/2;
				m_navswiper = [].slice.call(swiper.slides);
			    m_navswiper.forEach(function(item,index){
					var itempos =new Number(index*m_sw+m_itempos);
						item.setAttribute("data-pos",itempos);
						if(index==0){
							item.classList.add("active-nav");
							nodeList.navbar.style.cssText ='-webkit-transform:translate3d('+ itempos+'vw, 0px, 0px);';
                            setTimeout(function(){nodeList.navbar.style.visibility = 'visible';},300);					  
						}                           
			   }); 
            },
            "onTap": function(swiper,evt){ 
                var sci =swiper.clickedIndex;			
					goods_swiper.slideTo(sci);  
            }
         });
		 
         goods_swiper=new swiper('#goods-swiper',{
            "autoHeight": !0,
            "effect" : 'fade',
            "fade": {
              "crossFade": !0,
            },
            "lazyLoading" : !0,
            "touchMoveStopPropagation" : !1,
            "onSlideChangeStart": function(swiper){ 
                 var actIndex = swiper.activeIndex;	 
				custFuncs.updateMenu(actIndex);
				swiper.slides[actIndex].scrollTop=0;
				if(!m_navswiper[actIndex].dataset.first){
					nav_swiper.lockSwipes();
					goods_swiper.lockSwipes();
					custFuncs.loaddata(1,actIndex);
				}	
            },
            "onInit":function(swiper){   
					var minH = document.documentElement.clientHeight-nodeList.slideScroll.offsetTop;
					m_conswiper = [].slice.call(swiper.slides);
                    m_conswiper.forEach(function(item,index){
                       if(index==0){
                           swiper.slides[index].style.zIndex = "2";
						   custFuncs.loaddata(1,0,function(){
							   custFuncs.preloading(1,1);
						   });
						   m_navswiper[0].dataset.first = 'true';
                       }
					   item.style.minHeight = minH+"px";
                   });    
                                                                
            }
        });         


         virtualLink(function(evt){
         	location.href = evt.target.getAttribute("data-href");
         });

         wechat('open',data.shareData).init();
		 
         calendar().init(data);
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
		touch.on(nodeList.slideScroll,"scroll",evtFuncs.scroller);
    }
	
    //-------------自定义函数----------------
    var custFuncs = {
		        updateMenu:function(actIndex){
						var mbar = nodeList.navbar,mto = m_sw*actIndex+m_itempos;
						var activeNav = m_navswiper[actIndex];
						mbar.style['webkitTransform'] ='translate3d('+ mto+'vw, 0px, 0px)';	

						m_navswiper.forEach(function(item,index){
							if(actIndex==index){
								navIndex = index;
								item.classList.add("active-nav");
								m_conswiper[index].style.zIndex = "2";
							}else{
								item.classList.remove("active-nav");
								m_conswiper[index].style.zIndex = "0";
							}
						});

						if (!activeNav.classList.contains('swiper-slide-visible')) {
							if (navIndex>actIndex) {
								var thumbsPerNav = Math.floor(nav_swiper.width/activeNav.clientWidth)-1
									nav_swiper.slideTo(navIndex-thumbsPerNav)
							}else {
								nav_swiper.slideTo(navIndex)
							}   
						}
				},
				preloading:function(pageIndex,idx,callback){
					var typeid = m_navswiper[idx].dataset.cid;
                    if(loading) {
                        return;
                    }
                    loading =true;
                     ajax({
                         url: "/index.php?r=index/index&pageSize=10&ocid="+data.ocid+"&type="+typeid+"&pageIndex="+pageIndex,
                        onSuccess: function(json) {
                            loading=false;
                            if(json.loaded){
                                m_navswiper[idx].setAttribute("data-loaded",true);
                            }else{
                                m_navswiper[idx].setAttribute("data-page",pageIndex);
								if(pageIndex==1){
									m_navswiper[idx].setAttribute("data-first",'true');
								}
                               m_conswiper[idx].insertAdjacentHTML('beforeend', render({"data":json.data,"ocid":data.ocid,"imgsite":data.imgsite}));
							   if(typeof(callback)=="function"){
								   callback();
							   }
							  // goods_swiper.update();
                            }

                        },
                        onError: function(xmlHttp) {
                            loading=false;
                        }, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
                        onTimeout: function(xmlHttp) { }, // 超时触发
                        onAbort: function() {} // 网络中断时触发
                     });
				},
                loaddata:function(pageIndex,idx,callback){
					custFuncs.preloading(pageIndex,idx,function(){
						nav_swiper.unlockSwipes();
						goods_swiper.unlockSwipes();
						if(typeof(callback)=="function"){callback();}
						goods_swiper.update();
					});
                }
    }

    //-------------一切从这开始--------------
    var init = function(_data) {
		
        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
		
        // 子模块实例化
        initMod();

        // 绑定事件
        bindEvents();

    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};